package com.example.administrator.view;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.base.ActivityManager;
import com.example.administrator.base.BaseActivity;
import com.example.administrator.bean.LoginStatusBean;
import com.example.administrator.module.UrlDefine;
import com.example.administrator.testapk.R;
import com.example.administrator.utils.JsonUtils;
import com.example.administrator.utils.NetUtils;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import butterknife.BindView;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Response;


public class AtyResetPwd extends BaseActivity implements View.OnClickListener{

    private static final String TAG = "AtyResetPwd";

    @BindView(R.id.etPhoneNumber)
    EditText etPhoneNumber;
    @BindView(R.id.etCode) EditText etCode;
    @BindView(R.id.etPassword) EditText etPassword;
    @BindView(R.id.etCpwd) EditText etCpwd;

    @BindView(R.id.btnSendMsg)
    TextView btnSendMsg;
    @BindView(R.id.btnSubmitCode) TextView btnSubmitCode;
    @BindView(R.id.title_resetpwd) TitleBar title_resetpwd;

    private String countryCode="86";
    private int i = 60;//倒计时

    @Override
    protected int getLayoutResourceId() {
        return R.layout.aty_resetpwd;
    }

    @Override
    protected void init() {

        SMSSDK.initSDK(AtyResetPwd.this, UrlDefine.APP_KEY, UrlDefine.APP_SECRET);
        //initSDK方法是短信SDK的入口，需要传递您从MOB应用管理后台中注册的SMSSDK的应用AppKey和AppSecrete，如果填写错误，后续的操作都将不能进行
        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        //注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -1) {
                btnSendMsg.setText(i + " s");
            } else if (msg.what == -2) {
                btnSendMsg.setText("发送");
                btnSendMsg.setClickable(true);
                i = 60;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("asd", "event=" + event + "  result=" + result + "  ---> result=-1 success , result=0 error");
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后，返回MainActivity,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //构造请求参数
                        final Map<String, String> reqBody = new ConcurrentSkipListMap<>();
                        reqBody.put("phone", etPhoneNumber.getText().toString());
                        reqBody.put("password", etPassword.getText().toString());
                        reqBody.put("repeatPassword", etCpwd.getText().toString());
                        reqBody.put("verifyCode", etCode.getText().toString());

                        Log.e(TAG,"phone"+etPhoneNumber.getText().toString());
                        Log.e(TAG,"password"+etPassword.getText().toString());
                        Log.e(TAG,"repeatNewPassword"+etCpwd.getText().toString());
                        Log.e(TAG,"verifyCode"+etCode.getText().toString());

                        final String url = "http://119.23.231.114/App/user/resetPassword?phone=15277397109&password=77777777&repeatPassword=77777777&verifyCode=" + etCode.getText().toString();


                        //表示未登录
                       // NetUtils.getInstance().postDataAsynToNet(UrlDefine.ACTION_URL_RESETPWD, reqBody, new NetUtils.MyNetCall() {
                        NetUtils.getInstance().getDataAsynFromNet(url,new NetUtils.MyNetCall() {

                            @Override
                            public void success(Call call, Response response) throws IOException {
                                final String RegiMsgJsonStr = response.body().string();
//                                final String a = response.body().string();
                                Log.e(TAG,RegiMsgJsonStr);
                                //Log.e(TAG,response.message());
                               // Log.e(TAG,response.code() + "");
                             //   Log.e(TAG,url);
                                final LoginStatusBean loginStatusBean = JsonUtils.JsonStr2LoginStatusBean(RegiMsgJsonStr);
                                Log.e(TAG,"msg" + loginStatusBean.getMsg());
                                Log.e(TAG,"status" + loginStatusBean.getStatus());
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        if(loginStatusBean.getStatus() == 200){
//                                            toast("密码已更新，请返回登录界面");
//                                        }else{
//                                            toast(loginStatusBean.getMsg());
//                                        }
//                                    }
//                                });
                            }

                            @Override
                            public void failed(Call call, IOException e) {
                                Log.e(TAG,e.getMessage());
                            }
                        });
                        toast("短信验证成功");
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        toast("验证码已经发送");
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                } else if (result == SMSSDK.RESULT_ERROR) {
                    try {
                        Throwable throwable = (Throwable) data;
                        throwable.printStackTrace();
                        JSONObject object = new JSONObject(throwable.getMessage());
                        String des = object.optString("detail");//错误描述
                        int status = object.optInt("status");//错误代码
                        if (status > 0 && !TextUtils.isEmpty(des)) {
                            Log.e("asd", "des: " + des);
                            toast(des);
                            return;
                        }
                    } catch (Exception e) {
                        //do something
                    }
                }
            }
        }
    };

    @Override
    protected void initView() {
        title_resetpwd.setTitle("密码重置");
        title_resetpwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnSendMsg.setOnClickListener(this);
        btnSubmitCode.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String phoneNum = etPhoneNumber.getText().toString().trim();
        String pwd = etPassword.getText().toString().trim();
        String cpwd = etCpwd.getText().toString().trim();
        switch (v.getId()){
            case R.id.btnSendMsg:
                if (TextUtils.isEmpty(phoneNum)) {
                    toast("手机号码不能为空");
                }else {
                    SMSSDK.getVerificationCode(countryCode, phoneNum);
                    btnSendMsg.setClickable(false);
                    //开始倒计时
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (; i > 0; i--) {
                                handler.sendEmptyMessage(-1);
                                if (i <= 0) {
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            handler.sendEmptyMessage(-2);
                        }
                    }).start();
                }
                break;
            case R.id.btnSubmitCode:
                String code = etCode.getText().toString().trim();
                if (TextUtils.isEmpty(phoneNum)) {
                    toast("手机号码不能为空");
                    return;
                }
                if (TextUtils.isEmpty(code)) {
                    toast("验证码不能为空");
                    return;
                }
                SMSSDK.submitVerificationCode(countryCode, phoneNum, code);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 销毁回调监听接口
        SMSSDK.unregisterAllEventHandler();
        ActivityManager.getInstance().finishAllActivity();
    }

    }
